package com.javacv.plus.extensions.image.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.ProcessorResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_core.Size;
import org.bytedeco.opencv.global.opencv_imgproc;

/**
 * 按比例缩放步骤
 */
@Slf4j
public class ScaleStep implements ProcessorStep<ImageProcessor, ProcessorResult> {

    private final double factor;

    public ScaleStep(double factor) {
        if (factor <= 0) {
            throw new IllegalArgumentException("缩放因子必须大于0");
        }
        this.factor = factor;
    }

    @Override
    public ProcessorResult execute(ImageProcessor processor, ProcessorContext context) throws Exception {
        Mat currentImage = context.getAttribute("currentImage");
        if (currentImage == null) {
            throw new IllegalStateException("当前图像为空");
        }

        int newWidth = (int) (currentImage.cols() * factor);
        int newHeight = (int) (currentImage.rows() * factor);

        log.debug("按比例缩放: {}x{} -> {}x{} (因子: {})", 
                currentImage.cols(), currentImage.rows(), newWidth, newHeight, factor);

        Mat scaledImage = new Mat();
        Size newSize = new Size(newWidth, newHeight);
        
        opencv_imgproc.resize(currentImage, scaledImage, newSize, 0, 0, opencv_imgproc.INTER_LINEAR);

        context.setAttribute("currentImage", scaledImage);
        context.setAttribute("processedImage", scaledImage);

        log.debug("按比例缩放完成");
        return null;
    }

    @Override
    public String getStepName() {
        return "Scale";
    }

    @Override
    public int getPriority() {
        return 50;
    }
} 